package com.qipay.admin.utils;

import com.qipay.baas.model.ChannelType;
import com.qipay.channelType.ChannelTypeService;
import com.qipay.core.entity.DicConstance;
import com.qipay.core.utils.SpringContextUtil;
import com.qipay.user.entity.UserLevel;
import com.qipay.utils.CommonUtil;
import io.jsonwebtoken.lang.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by back on 2016/6/25.
 */
public class SiteHelper {

    private static final int dayNeedFuck = 1000 * 3600 * 24;
    public static final BigDecimal decimalFor100 = BigDecimal.valueOf(100.00);

    /**
     * 比较两个日期的大小
     *
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差毫秒数
     * @throws ParseException
     */
    public static long daysCompare(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        return time2 - time1;
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (dayNeedFuck);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 字符串的日期格式的计算
     */
    public static int daysBetween(String smdate, String bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (dayNeedFuck);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 返回两数相除的百分比
     *
     * @param num1 分子
     * @param num2 分母
     * @return 返回两数相除的百分比
     * @throws ParseException
     */
    public static String getPercent(double num1, float num2) {
        if (num2 > 0) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            return numberFormat.format(num1 / num2 * 100);
        }
        return "0";
    }

    /**
     * 返回人性化人民币
     */
    public static String getMoneyFormat(Double money) {
        if (money == null) {
            return "0";
        }
        if (money >= 10000) {
            if (money % 10000 == 0) {
                return (int) (money / 10000) + "万";
            }
            return money / 10000 + "万";
        } else if (money >= 1000) {
            DecimalFormat moneyFormat = new DecimalFormat(",###");
            return moneyFormat.format(money);
        } else if (money > 1) {
            DecimalFormat moneyFormat = new DecimalFormat("#.###");
            return moneyFormat.format(money);
        } else {
            return getMoneyFormatAll(money);
        }
    }

    /**
     * 返回人性化人民币
     */
    public static String getMoneyFormatAll(Double money) {
        if (money == null) {
            return "0";
        }
        return new DecimalFormat("0.00").format(money);
    }

    public static String getMoneyFormatAll(BigDecimal money) {
        if (money == null) {
            return "0";
        }
        return new DecimalFormat("0.00").format(money);
    }

    public static String getMoneyFormatAll(Long money) {
        if (money == null) {
            return "0";
        }
        if (money >= 1000) {
            DecimalFormat moneyFormat = new DecimalFormat("0000.0#");
            return moneyFormat.format(money);
        }
        return new DecimalFormat("0.00").format(money);
    }

    public static String getProjectStatusStyle(int status, int proStatus) {
        if (status == 0) {
            return "rz-tag-audit";
        }
        if (status == 200 && proStatus == 1) {
            return "rz-tag-warm";
        }
        if (status == 200 && proStatus == 2) {
            return "rz-tag-ing";
        }
        if (status == 200 && proStatus == 200) {
            return "rz-tag-suc";
        }
        return "";
    }

    public static String removeTag(String htmlStr) {
        if (!StringUtils.isEmpty(htmlStr)) {
            String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // script
            String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // style
            String regEx_html = "<[^>]+>"; // HTML tag
            String regEx_space = "\\s+|\t|\r|\n";// other characters

            Pattern p_script = Pattern.compile(regEx_script,
                    Pattern.CASE_INSENSITIVE);
            Matcher m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll("");
            Pattern p_style = Pattern
                    .compile(regEx_style, Pattern.CASE_INSENSITIVE);
            Matcher m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll("");
            Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            Matcher m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll("");
            Pattern p_space = Pattern
                    .compile(regEx_space, Pattern.CASE_INSENSITIVE);
            Matcher m_space = p_space.matcher(htmlStr);
            htmlStr = m_space.replaceAll(" ");
        }
        return htmlStr;
    }

    public static String getStrReplace(String str, int start, int end, char replaceStr) {
        if (!StringUtils.isEmpty(str) && str.length() >= end) {
            char[] chars = str.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                if (i >= start && i <= end) {
                    chars[i] = replaceStr;
                }
            }
            return new String(chars);
        }
        return str;
    }

    public static String cleanXSS(String value) {
        //You'll need to remove the spaces from the html entities below
        value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
        value = value.replaceAll("'", "&#39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        return value;
    }

    /*
     * 返回资金明细里的类型值
     * */
    public static String getFundTradeTypeStr(byte trade) {
//        TradeTypeEnum tradeTypeEnum = TradeTypeEnum.values()[(int) trade];
//        return tradeTypeEnum.getName();
        return "";
    }

    public static String getDaysStr(Date start, int collectDays, int projectStatus) throws ParseException {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(start);
        gc.add(5, collectDays);
        // sdf.format(gc.getTime());
        int timeLimit = 0;
        if (projectStatus == 1) {
            timeLimit = daysBetween(gc.getTime(), new Date());
        } else {
            timeLimit = daysBetween(new Date(), gc.getTime());
        }
        if (projectStatus == 200) {
            return "已成功";
        }
        //int timeLimit = daysBetween(new Date(), gc.getTime());
        return timeLimit + "天";
    }

    public static String getEmptyStr(Object obj) {
        return getEmptyStr(obj, "");
    }

    public static String getEmptyStr(Object obj, String defaultStr) {
        if (!StringUtils.isEmpty(obj)) {
            return obj.toString();
        }
        return defaultStr;
    }

    /**
     * 获取帐号的状态字串
     *
     * @param accoutState
     * @return
     */
    public static String getAccountString(Byte accoutState) {
        if (accoutState == null) return "禁用";
        if (accoutState == 2) return "启用";
        if (accoutState == 1) return "审核中";
        return "禁用";
    }

    /**
     * 获取签约状态字串
     *
     * @param contractState
     * @return String
     */
    public static String getContractString(Byte contractState) {
        if (contractState == null) return "未签约";
        if (contractState == 1) return "已签约";
        if (contractState == 0) return "未签约";
        return "未知";
    }

    /**
     * 获取渠道的类型字串
     *
     * @param contractState
     * @return
     */
    public static String getChannelTypeString(Byte contractState) {
        ChannelTypeService channelTypeService = (ChannelTypeService) SpringContextUtil.getBean(ChannelTypeService.class);
        if (contractState == null) return "未知";
        ChannelType channelType = channelTypeService.findById(contractState);
        return channelType==null?"":channelType.getName();
    }

    /**
     * 获取渠道状态值字串
     *
     * @param contractState
     * @return
     */
    public static String getChannelStateString(Byte contractState) {
        if (contractState == null) return "禁用";
        if (contractState == 1) return "禁用";
        if (contractState == 0) return "启用";
        return "禁用";
    }

    public static String getProductTypeState(Byte contractState) {
        if (contractState == null) return "未开通";
        if (contractState == 1) return "未开通";
        if (contractState == 0) return "开通";
        return "未开通";
    }

    public static String getNetState(Byte contractState) {
        if (contractState == null) return "未入网";
        if (contractState == 1) return "未入网";
        if (contractState == 0) return "入网";
        return "禁用";
    }

    public static String getProductType(Byte contractState) {
        if (contractState == null) return "无";
        if (contractState == 1) return "快捷支付";
        if (contractState == 2) return "QQ支付";
        return "无";
    }

    //米贝提现状态
    public static String getMiBeiState(Byte contractState) {
        if (contractState == null) return "无";
        if (contractState == 0) return "成功";
        if (contractState == 1) return "正在提现";
        if (contractState == 2) return "失败";
        return "无";
    }

    //娱秀状态
    public static String getYuxiuState(Byte contractState) {
        if (contractState == null) return "无";
        if (contractState == 0) return "成功";
        if (contractState == 1) return "预付";
        if (contractState == 2) return "失败";
        return "无";
    }

    public static String getMibeiPayType(Byte contractState) {
        if (contractState == null) return "";
        if (contractState == 1) return "对公";
        if (contractState == 0) return "对私";
        return "";
    }

    public static String getYuXiuPayId(Byte contractState) {
        if (contractState == null) return "";
        if (contractState == 0) return "额度代付";
        if (contractState == 1) return "普通代付";
        return "";
    }

    /**
     * 按值获取用户等级枚举
     *
     * @param level
     * @return
     */
    public static UserLevel getUserLevelByLevel(Integer level) {
        if (level == null) return UserLevel.CP;
        if (level == 200) return UserLevel.AGENT;
        if (level == 1000 || level == 500) return UserLevel.ADMIN;
        return UserLevel.CP;
    }

    /**
     * 按值获取用户等级字串
     *
     * @param level
     * @return
     */
    public static String getUserLevelStrByLevel(Integer level) {
        if (level == null) return "商户（CP）";
        if (level == 200) return "代理商";
        if (level == 500) return "管理员";
        if (level == 1000) return "管理员";
        if (CommonUtil.equalsNumber(level, UserLevel.ADMIN_Hao.getCode())) return "供号商";
        return "商户（CP）";
    }

    /**
     * 按值获取用户等级字串
     *
     * @param level
     * @return
     */
    public static String getUserLevelStrByLevel(UserLevel level) {

        if (level == null) return "商户（CP）";
        if (level == UserLevel.AGENT) return "代理商";
        if (level == UserLevel.ADMIN) return "管理员";
        return "商户（CP）";
    }

    /***
     * yyyy-MM-dd HH:mm:ss
     * @param date
     * @return
     */
    public static String getDefaultTimeFormat(Date date) {

        String fmt = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (null != date) {
            fmt = sdf.format(date);
        }

        return fmt;
    }

    /***
     * yyyy-MM-dd
     * @param date
     * @return
     */
    public static String getSimpleTimeFormat(Date date) {

        String fmt = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        if (null != date) {
            fmt = sdf.format(date);
        }

        return fmt;
    }

    public static String getTimeFormat(Date date) {

        String fmt = "";
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        if (null != date) {
            fmt = sdf.format(date);
        }

        return fmt;
    }

    /***
     * 将 11113.36633332 格式化 11,113.37 元
     * @param number
     * @param divide
     * @return
     */
    public static String formatMoney(Object number, Double divide) {

        return String.format("%.2f ", formatDouble(number, divide));
    }

    public static String formatMoneySimple(Object number, Double divide) {

        return String.format("%.2f", formatDouble(number, divide));
    }

    private static double formatDouble(Object number, Double divide) {

        // check
        Assert.notNull(!divide.equals(0));

        // init
        Double num = 0d;
        if (null != number) {
            if (number instanceof Double) {
                num = (Double) number;
            } else {
                num = Double.valueOf(number.toString());
            }
        }
        divide = null == divide ? 1 : divide;

        return num / divide;
    }

    public static String formatMoney(Object number) {

        return formatMoney(number, 1d);
    }

    public static String formatMoneySimple(Object number) {

        return formatMoneySimple(number, 1d);
    }

    public static String formatNumber(Object number, Double divide) {

        // check
        Assert.notNull(!divide.equals(0));

        // init
        Double num = 0d;
        if (null != number) {
            if (number instanceof Double) {
                num = (Double) number;
            } else {
                num = Double.valueOf(number.toString());
            }
        }
        divide = null == divide ? 1 : divide;

        // convert
        return String.format("%.2f", num / divide);
    }

    public static String formatNumber(Object number) {
        return formatNumber(number, 1d);
    }

    /***
     *
     * 将 0.13579 格式化 0.13579
     * @param number
     * @return
     */
    public static String formatPercentage(Double number) {

        number = null == number ? 0d : number;
        return String.format("%.2f%%", number * 100);
    }

    public static String formatPercentage(BigDecimal number) {

        double num = null == number ? 0d : number.doubleValue();
        return String.format("%.2f%%", num * 100);
    }

    public static void main(String[] args) {

        System.out.println(SiteHelper.formatMoney(11113.36633332));
        System.out.println(SiteHelper.getMoneyFormat(11111111111.3663));
        System.out.println(SiteHelper.getMoneyFormatAll(1111111111111113.3663));
        System.out.println(SiteHelper.getMoneyFormatAll(1111111113l));
        System.out.println(SiteHelper.getMoneyFormatAll(new BigDecimal(1111111111111113.3663)));
        System.out.println(SiteHelper.formatPercentage(0.13579));
        System.out.println(SiteHelper.formatPercentage(new BigDecimal(0.13579)));
    }
}
